package pl.leader100.rest;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import pl.leader100.rest.data.Doc;
import pl.leader100.rest.data.Doc3;
import pl.leader100.rest.data.DocDao;

public class ListDocByCat3 {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;

	String role;
	String date;
	String locale;
	String year = "2011/2012";
	String course = "junior_leader_r1";
	String category;

	public ListDocByCat3(UriInfo uriInfo, Request request, String role,
			String date, String locale, String year, String course,
			String category) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.role = role;
		this.date = date;
		this.locale = locale;
		this.year = year;
		this.course = course;
		this.category = category;
	}

	// Application integration
	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public List<Doc3> getDocByCat3() {
		try {

			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date d;
			d = df.parse(date);

			Calendar cal = Calendar.getInstance();
			cal.setTime(d);
			cal.add(Calendar.MONTH, -1);
			String previousDate = df.format(cal.getTime());

			cal.setTime(d);
			cal.add(Calendar.MONTH, +1);
			String nextDate = df.format(cal.getTime());

			List<Doc> docs0 = DocDao.GetInstance().getDocsByCat(role,
					previousDate, locale, year, course, category);
			List<Doc> docs1 = DocDao.GetInstance().getDocsByCat(role, date,
					locale, year, course, category);
			List<Doc> docs2 = DocDao.GetInstance().getDocsByCat(role, nextDate,
					locale, year, course, category);

			if (docs1 == null)
				throw new RuntimeException("Get: Doc with " + role + " " + date
						+ " " + locale + " not found");
			String[] title = new String[3];
			String[] path = new String[3];
			String[] keys = new String[3];

			List<Doc3> doc3s = new ArrayList<Doc3>();

			for (Doc doc1 : docs1) {
				Doc doc0 = docs0.get(docs1.indexOf(doc1));
				Doc doc2 = docs2.get(docs1.indexOf(doc1));

				title[0] = doc0.getTitle();
				title[1] = doc1.getTitle();
				title[2] = doc2.getTitle();

				path[0] = doc0.getPath();
				path[1] = doc1.getPath();
				path[2] = doc2.getPath();

				Doc3 doc3 = new Doc3(title, path, locale, course, category,
						doc1.getMimetype());

				doc3.setUniqueKey_previous(doc0.getUniqueKey());
				doc3.setUniqueKey_previous(doc1.getUniqueKey());
				doc3.setUniqueKey_previous(doc2.getUniqueKey());

				doc3s.add(doc3);
			}
			return doc3s;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

}
